package com.nexgo.payment.trans.settle;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.constrant.SettleOpType;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.databases.SettleInfo;
import com.nexgo.payment.fragment.ProgressDialogFragment;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.trans.AbsTransActivity;
import com.nexgo.payment.trans.logout.LogoutActivity;
import com.nexgo.payment.ui.BaseActivity;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.ItemLinearAlignLayout;
import com.nexgo.payment.widget.ItemLinearLayout;
import com.nexgo.payment.widget.TitleBuilder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 交易结算界面
 *
 * @author 谭忠扬-YuriTam //xiaox 2017/9/4 下午4:26
 * @time 2017年8月29日
 */
public class SettleActivity extends AbsTransActivity<SettleContract.Presenter> implements SettleContract.View, BaseActivity.DownTimerListener {
    private static final String OPERATE_TYPE = "operateType";   //操作类型

    @BindView(R.id.title_tv_right)
    TextView tvTitleRight;
    @BindView(R.id.item_merchant_name)
    ItemLinearLayout itemMerchantName;
    @BindView(R.id.item_merchant_no)
    ItemLinearLayout itemMerchantNo;

    @BindView(R.id.item_terminal_no)
    ItemLinearLayout itemTerminalNo;
    @BindView(R.id.item_batch_no)
    ItemLinearLayout itemBatchNo;
    @BindView(R.id.item_date_time)
    ItemLinearLayout itemDateTime;
    @BindView(R.id.item_inner_debit)
    ItemLinearAlignLayout itemInnerDebit;
    @BindView(R.id.item_inner_credit)
    ItemLinearAlignLayout itemInnerCredit;
    @BindView(R.id.item_external_debit)
    ItemLinearAlignLayout itemExternalDebit;
    @BindView(R.id.item_external_credit)
    ItemLinearAlignLayout itemExternalCredit;
    //lr
    @BindView(R.id.item_scan_debit)
    ItemLinearAlignLayout itemScanDebit;
    @BindView(R.id.item_scan_credit)
    ItemLinearAlignLayout itemScanCredit;
    //end
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.btn_cancel)
    Button btnCancel;

    private ProgressDialogFragment mDialogFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settle);
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        int opType = bundle.getInt(OPERATE_TYPE, 0);
        SettleOpType settleOpType = SettleOpType.values()[opType];
        initTitle(settleOpType);
        initView(settleOpType);
        new SettlePresenter(this, Repository.getInstance(), settleOpType);
    }

    private void initView(SettleOpType settleOpType) {
        switch (settleOpType) {
            case REPRINT_SETTLE_INFO:
            case PRINT_SUM_INFO:
                btnCancel.setVisibility(View.INVISIBLE);
                btnConfirm.setVisibility(View.INVISIBLE);
                break;
            default:
                break;
        }
    }

    //初始化标题栏
    private void initTitle(SettleOpType settleOpType) {
        new TitleBuilder(this)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(SettleOpType.REPRINT_SETTLE_INFO.equals(settleOpType) ? R.string.last_settle_title : R.string.trans_settle_title))
                .build();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left, R.id.btn_confirm, R.id.btn_cancel})
    public void onClicked(View view) {
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_iv_left:
            case R.id.btn_cancel:
                quitTrans();
                break;
            case R.id.btn_confirm:
                cancelDownTimer();
                //开始结算
                mPresenter.doSettle();
                break;
            default:
                break;
        }
    }

    @Override
    public void intent2Logout() {
        intent2Activity(LogoutActivity.class);
        quitTrans();
    }

    @Override
    public void showStatistics(SettleInfo sumInfo, boolean isCountDown) {
        //商户名称
        itemMerchantName.setRightText(sumInfo.getMerchantName());
        //商户编号
        itemMerchantNo.setRightText(sumInfo.getMerchantId());
        //终端编号
        itemTerminalNo.setRightText(sumInfo.getTerminalId());
        //批次号
        itemBatchNo.setRightText(sumInfo.getBatchNum());
        //日期时间
        itemDateTime.setRightText(StringUtils.formatDateTime(sumInfo.getDate(), sumInfo.getTime()));
        //内卡借记-笔数-金额
        itemInnerDebit.setCenterText(String.valueOf(sumInfo.getStatistics().getDebitNum()));
        itemInnerDebit.setRightText(StringUtils.formatAmount(String.valueOf(sumInfo.getStatistics().getDebitAmt()), SysConstant.FUND_DIGITS));
        //内卡贷记-笔数-金额
        itemInnerCredit.setCenterText(String.valueOf(sumInfo.getStatistics().getCreditNum()));
        itemInnerCredit.setRightText(StringUtils.formatAmount(String.valueOf(sumInfo.getStatistics().getCreditAmt()), SysConstant.FUND_DIGITS));
        //外卡借记-笔数-金额
        itemExternalDebit.setCenterText(String.valueOf(sumInfo.getInterStatistics().getDebitNum()));
        itemExternalDebit.setRightText(StringUtils.formatAmount(String.valueOf(sumInfo.getInterStatistics().getDebitAmt()), SysConstant.FUND_DIGITS));
        //外卡贷记-笔数-金额
        itemExternalCredit.setCenterText(String.valueOf(sumInfo.getInterStatistics().getCreditNum()));
        itemExternalCredit.setRightText(StringUtils.formatAmount(String.valueOf(sumInfo.getInterStatistics().getCreditAmt()), SysConstant.FUND_DIGITS));

        //lr
        //扫码消费-笔数-金额
        itemScanDebit.setCenterText(String.valueOf(sumInfo.getScanStatistics().getDebitNum()));
        itemScanDebit.setRightText(StringUtils.formatAmount(String.valueOf(sumInfo.getScanStatistics().getDebitAmt()), SysConstant.FUND_DIGITS));
        //扫码退货-笔数-金额
        itemScanCredit.setCenterText(String.valueOf(sumInfo.getScanStatistics().getCreditNum()));
        itemScanCredit.setRightText(StringUtils.formatAmount(String.valueOf(sumInfo.getScanStatistics().getCreditAmt()), SysConstant.FUND_DIGITS));

        //开始倒计时
        if (isCountDown) setDownTimer(SysConstant.TIME_OUT_60, this);
    }

    @Override
    public void showSettleFail() {
        ToastUtils.showToast(getString(R.string.settle_fail));
        quitTrans();
    }

    @Override
    public void showNoTransRecord() {
        ToastUtils.showToast(getString(R.string.has_no_trans_record));
        quitTrans();
    }

    @Override
    public void showSettleSuccessfully() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_SUCCESS);
        dialogFragment.setTitleText(getString(R.string.settle_success));
        dialogFragment.setPositionText(getString(R.string.confirm), SysConstant.TIME_OUT_5);
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onConfirm() {
                quitTrans();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showWhetherPrintTransDetail(boolean isErr) {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(isErr ? R.string.whether_print_Error_detail : R.string.whether_print_settle_detail), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm), SysConstant.TIME_OUT_5);
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                //lr add
                mPresenter.cancelPrintDetail();
//                quitTrans();
            }

            @Override
            public void onConfirm() {
                mPresenter.startPrintTransDetail(isErr);
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showPrintInitErr() {
        ToastUtils.showToast(getString(R.string.print_err));
        quitTrans();
    }

    @Override
    public void setPrintingIndicator(boolean active) {
        if (active) {
            if (mDialogFragment == null) {
                mDialogFragment = new ProgressDialogFragment();
            }
            mDialogFragment.setTipTitle(getString(R.string.printing));
            mDialogFragment.setTip(getString(R.string.pls_wait));
            mDialogFragment.setCancelable(false);
            mDialogFragment.setOnDialogListener(() -> mPresenter.cancelPrintDetail());
            mDialogFragment.show(getSupportFragmentManager(), null);
        } else {
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
                mDialogFragment = null;
            }
        }
    }

    @Override
    public void showPrintSuccessfully() {
        quitTrans();
    }

    @Override
    public void showPrintLackPaper(boolean isRePrint, SettleOpType opType) {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.print_lack_paper));
        dialogFragment.setContentText(getString(R.string.print_lack_desc), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                quitTrans();
            }

            @Override
            public void onConfirm() {
                if (opType == null) {
                    mPresenter.continuePrintDetail();
                } else {
                    switch (opType) {
                        case PRINT_SUM_INFO:
                            mPresenter.startPrintSum();
                            break;
                        default:
                            mPresenter.startPrintSettle(isRePrint);
                            break;
                    }
                }
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showPrintFail(String failDesc) {
        if (!TextUtils.isEmpty(failDesc)) {
            ToastUtils.showToast(failDesc);
        }
        quitTrans();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(String.valueOf(secondsUntilFinished));
    }

    @Override
    public void onFinish() {
        tvTitleRight.setText("0");
        quitTrans();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDownTimer();
        mPresenter.destroy();
    }

    public static Intent newInstance(Context context, SettleOpType opType) {
        Intent intent = new Intent(context, SettleActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(OPERATE_TYPE, opType.ordinal());
        intent.putExtras(bundle);
        return intent;
    }
}
